# vim: ai ts=4 sts=4 et sw=4

from django.conf import settings
from django.http import HttpResponse
from tvapi.thetvdb.models import *

from django.forms.models import model_to_dict
from django.utils import simplejson as json

from tvapi.thetvdb.views import GetImageFromUrl
from django.core.files import File

#from tvapi.util import JsonResponse
from tvapi.api.util import JsonResponse

def Search(request, name):
    """ Search by Series and Actor """

    response = {}

    series = Series.objects.filter(SeriesName__icontains=name).order_by('-Rating')
    seriesList = []
    for s in series:
        seriesList.append({'series_id': s.id, 'series_name': s.SeriesName})
    response['Series'] = seriesList

    actors = Actor.objects.filter(name__icontains=name).order_by('name')
    actorList = []
    for a in actors:
        actorList.append({'actor_id': a.id, 'actor_name': a.name})
    response['Actors'] = actorList

    return JsonResponse(response)


def SeriesSearch(request, title):
    series = Series.objects.filter(SeriesName__icontains=title).order_by('-Rating')
    response = []
    for s in series:
	#response['name'] = s.SeriesName
	#response.append({'id': s.id, 'name': s.SeriesName})
	responseDict = model_to_dict(s, fields=["id", "SeriesName"])
	response.append(responseDict)

        
    #return HttpResponse(json.dumps(response))
    #return HttpResponse(repr(series.values()))
    return JsonResponse(response)


def SeriesDetails(request, id):
    s = Series.objects.get(id=id)
    response = {}
    response['id'] = id
    response['FirstAired'] = s.FirstAired
    response['AirDay'] = s.Airs_DayOfWeek
    response['AirTime'] = s.Airs_Time
    response['Runtime'] = s.Runtime
    response['Network'] = s.Network
    response['Rating'] = s.Rating
    response['Status'] = s.Status
    response['Overview'] = s.Overview
    response['Poster'] = s.poster.image_path
    
    # Actors
    actorObj = ActorRoles.objects.filter(series=s)
    actorList = []
    for a in actorObj:
        actorList.append({'id': a.actor.id, 'Name': a.actor.name}) # double check the actor id
        
    response['Actors'] = actorList      

    return JsonResponse(response)

# id = Series ID
# using 2/5 fields from the Series model
def SeasonList(request, id):
    s = Series.objects.get(id=id)

    seasons = Season.objects.filter(series=s).order_by("season_number")
    seasonList = []
    for season in seasons:
        if season.season_number == 0:
            continue
           
        seasonList.append({'id': season.id, 'Number': season.season_number})

    response = {}
    response['Seasons'] = seasonList

    return JsonResponse(response)


# id = Season id
# using 3/29 fields from the Episodes model
def EpisodeList(request, id):
#s = Series.objects.get(id=id)
    episodes = Episodes.objects.filter(season__id = id).order_by("EpisodeNumber") # was "seasonid", but stopped working after Actor changes

#    seasons = Season.objects.filter(series=s).order_by("season_number")
#    seasonList = []
#    for season in seasons:
    		
#    	episodes = Episodes.objects.filter(seasonid=season.id).order_by("EpisodeNumber")
    episodeList = []
    for episode in episodes:
	episodeList.append({'id': episode.id, 'Number': episode.EpisodeNumber, 'Name': episode.EpisodeName})
	
#	seasonList.append({'id': season.id, 'Number': season.season_number, 'Episodes': episodeList})
    #seasonList.append({'id': season.id, 'Number': season.season_number, season.id: episodeList})

    #response = {}
    #response['Seasons'] = seasonList
    response = {}
    response['Episodes'] = episodeList


    return JsonResponse(response)

# id = Episode ID
def EpisodeDetail(request, id):
    episode = Episodes.objects.get(id=id)

    response = {}
    response['id'] = episode.id
    response['Number'] = episode.EpisodeNumber
    response['Name'] = episode.EpisodeName
    response['Aired'] = episode.FirstAired
    response['Season'] = episode.SeasonNumber
    response['Overview'] = episode.Overview
    response['Image'] = episode.filename.image_path

    return JsonResponse(response)

#id = Actor ID
# returns the Actor: Name, Role, and List of Series
def ActorDetail(request, actor_id, series_id):
    actor = Actor.objects.get(id=actor_id)
    if int(series_id) > 0:
        role = ActorRoles.objects.get(actor=actor, series__id=series_id)
    
    response = {}
    response['id'] = actor.id
    response['Name'] = actor.name
    if int(series_id) > 0:
        response['Role'] = role.Role
    
    try:
        response['Image'] = actor.image.image_path
    except:
        response['Image'] = settings.IMAGE_BLANK

    actorRoles = ActorRoles.objects.filter(actor=actor)
    roleList = []

    for r in actorRoles:
        date = r.series.FirstAired.split('-')
    	roleList.append({
            'series_id': r.series.id, 
            'series_name': r.series.SeriesName, 
            'series_role': r.Role,
            'series_date': date[0]
            })

    response['roles'] = roleList

    return JsonResponse(response)


#from django.forms.models import model_to_dict
def ListLanguages(request):
#    languages = Languages.objects.all()
#    response = []
#    for language in languages:
#	response.append({'name': language.name, 'id': language.id})
#    return HttpResponse(json.dumps(response))

    languages = Language.objects.all()
    response = []
    for language in languages:
	langDict = model_to_dict(language, exclude=["date_added", "last_modified", "abbreviation"])
	response.append(langDict)
    return JsonResponse(response)


import StringIO
#def get_image(response):
#    p = urlretrieve("http://thetvdb.com/banners/posters/82066-6.jpg")
#    img = Image.open(p[0])
#    mypath = "/home/justinhomi/someimage789.jpg"
#    img.thumbnail(settings.THETVDB_DEFAULT_MAX_THUMBNAIL_SIZE, Image.ANTIALIAS)
#    img.save(mypath, 'JPEG')
#    return HttpResponse(open(mypath).read(), mimetype="image/jpeg")

def get_image(response, obj_id, type, img_id):
       
    img_partial_path = type + '/' + img_id + '.jpg'
    img_path = settings.THETVDB_BANNERS_ROOT + img_partial_path
    
    if not os.path.exists(img_path):
        if (type=='actors'):
            o = Actor.objects.get(id=obj_id)
        elif type=='posters':
            o = Series.objects.get(id=obj_id)
        urlimage = GetImageFromUrl(settings.THETVDB_IMAGE_URL_BASE + img_partial_path) 
        filename = os.path.basename(img_partial_path)
        #if (type=='actors'):
        o.image.image_file.save(filename, File(open(urlimage[0])))
        #elif type=='posters':
         #   o.poster.image_file.save(filename, File(open(urlimage[0])))
    return HttpResponse(open(img_path).read(), mimetype="image/jpeg")
    
def get_episode_image(response, obj_id, type, series_id, img_id):
    img_partial_path = type + '/' + series_id + '/' + img_id + '.jpg'
    img_path = settings.THETVDB_BANNERS_ROOT + img_partial_path
    if not os.path.exists(img_path):
        series_path = settings.THETVDB_BANNERS_ROOT + type + '/' + series_id
        if not os.path.exists(series_path):
            os.mkdir(series_path)
        o = Episodes.objects.get(id=obj_id)
        urlimage = GetImageFromUrl(settings.THETVDB_IMAGE_URL_BASE + img_partial_path) 
        filename = os.path.basename(img_partial_path)
        o.image.image_file.save(filename, File(open(urlimage[0])))
    return HttpResponse(open(img_path).read(), mimetype="image/jpeg")
    

